// store/modules/dictionaryStore.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

interface DictionaryItem {
  label: string
  value: string
}

interface DictionaryState {
  dictionaries: Map<string, DictionaryItem[]>
  loading: Set<string>
}

export const useDictionaryStore = defineStore('dictionary', () => {
  // 状态
  const dictionaries = ref(new Map<string, DictionaryItem[]>())
  const loading = ref(new Set<string>())

  // 常用字典类型常量
  const DICTIONARY_TYPES = {
    // 自主可控等级
    INDEPENDENT_CONTROL_LEVEL: 'INDEPENDENT_CONTROL_LEVEL',
    // 是/否
    YORN: 'YORN',
    // 元器件分类 - 特殊处理，value 使用 code
    COM_CLASSIFICATION: 'COM_CLASSIFICATION',
    ELE_CLASSIFICATION: 'ELE_CLASSIFICATION',

    MA_CLASSIFICATION: 'MA_CLASSIFICATION',

    // 解决方式
    SOLUTION_PLAN: 'SOLUTION_PLAN',
    // 获取渠道
    ACQUISITION_CHANNEL: 'ACQUISITION_CHANNEL',
    // 节点类型
    NODE_TYPE: 'NODE_TYPE',
    // 是否WKB
    IS_WKB: 'IS_WKB',
    // 对外依存度
    EXTERNAL_DEPENDENCE: 'EXTERNAL_DEPENDENCE',
    // 必要等级
    NECESSITY_LEVEL: 'NECESSITY_LEVEL',
    // 安全等级颜色
    SAFETY_LEVEL_COLOR: 'SAFETY_LEVEL_COLOR',
    // 机载设备重要程度类别
    IMPORTANT_LEVEL: 'IMPORTANT_LEVEL',
    // 材料品种
    MATERIAL_VARIETY: 'MATERIAL_VARIETY',
    // 材料使用分类
    USAGE_CLASSIFICATION: 'USAGE_CLASSIFICATION',
    // 进口机电选用必要性
    IE_NECESSITY_LEVEL: 'IE_NECESSITY_LEVEL',
    // 进口软件，【对标典型国产产品是否鉴定/验收】
   IS_ACCEPT: 'IS_ACCEPT',

    // 可以继续添加其他字典类型
  }

  // 需要特殊处理的字典类型（value 使用 code） COM_
  const SPECIAL_VALUE_TYPES = [
    DICTIONARY_TYPES.COM_CLASSIFICATION,
    DICTIONARY_TYPES.ELE_CLASSIFICATION,
    DICTIONARY_TYPES.MA_CLASSIFICATION,
    // 可以添加其他需要特殊处理的类型
  ]

  // 处理字典数据
  const processDictionaryData = (type: string, data: any[]): DictionaryItem[] => {
    // 如果是特殊类型，value 使用 code
    if (SPECIAL_VALUE_TYPES.includes(type)) {
      return data
    }

    // 普通类型，value 使用 text
    return data.map((item: any) => ({
      label: item.text,
      value: item.text
    }))
  }

  // 获取字典数据
  const getDictionary = async (type: string): Promise<DictionaryItem[]> => {
    // 如果正在加载中，直接返回空数组
    if (loading.value.has(type)) {
      return []
    }

    // 如果已有缓存数据，直接返回
    if (dictionaries.value.has(type)) {
      return dictionaries.value.get(type)!
    }

    try {
      loading.value.add(type)

      const res = await "/api/constant/list".get({ type })

      // 根据类型处理数据
      const data = processDictionaryData(type, res.data)

      // 更新缓存
      dictionaries.value.set(type, data)
      return data
    } catch (error) {
      console.error(`获取字典 ${type} 失败:`, error)
      ElMessage.error(`获取字典数据失败: ${type}`)
      return []
    } finally {
      loading.value.delete(type)
    }
  }

  // 批量获取字典（支持并发）
  const getDictionaries = async (types: string[]): Promise<Record<string, DictionaryItem[]>> => {
    const results: Record<string, DictionaryItem[]> = {}

    // 去重并过滤已缓存的类型
    const uniqueTypes = Array.from(new Set(types))
    const typesToFetch = uniqueTypes.filter(type => !dictionaries.value.has(type))

    // 并发获取未缓存的字典
    if (typesToFetch.length > 0) {
      const promises = typesToFetch.map(type => getDictionary(type))
      await Promise.all(promises)
    }

    // 从缓存中获取所有数据
    uniqueTypes.forEach(type => {
      results[type] = dictionaries.value.get(type) || []
    })

    return results
  }

  // 预加载常用字典
  const preloadCommonDictionaries = async (): Promise<void> => {
    const commonTypes = [
      DICTIONARY_TYPES.INDEPENDENT_CONTROL_LEVEL,
      DICTIONARY_TYPES.YORN,
      DICTIONARY_TYPES.COM_CLASSIFICATION,
      DICTIONARY_TYPES.SOLUTION_PLAN,
      DICTIONARY_TYPES.ACQUISITION_CHANNEL,
      DICTIONARY_TYPES.NODE_TYPE,
      DICTIONARY_TYPES.IS_WKB,
      DICTIONARY_TYPES.EXTERNAL_DEPENDENCE,
      DICTIONARY_TYPES.NECESSITY_LEVEL,
      DICTIONARY_TYPES.SAFETY_LEVEL_COLOR,
      DICTIONARY_TYPES.IMPORTANT_LEVEL,
      DICTIONARY_TYPES.MATERIAL_VARIETY,
      DICTIONARY_TYPES.USAGE_CLASSIFICATION,
      DICTIONARY_TYPES.IE_NECESSITY_LEVEL,
      DICTIONARY_TYPES.IS_ACCEPT,
      DICTIONARY_TYPES.ELE_CLASSIFICATION,
      DICTIONARY_TYPES.MA_CLASSIFICATION,
    ]

    await getDictionaries(commonTypes)
  }

  // 清除指定字典缓存
  const clearDictionary = (type: string): void => {
    dictionaries.value.delete(type)
  }

  // 清除所有缓存
  const clearAll = (): void => {
    dictionaries.value.clear()
  }

  // 获取字典选项（同步方法，用于组件中）
  const getDictionaryOptions = (type: string): DictionaryItem[] => {
    return dictionaries.value.get(type) || []
  }

  // 判断是否是特殊类型（用于外部需要知道的场景）
  const isSpecialType = (type: string): boolean => {
    return SPECIAL_VALUE_TYPES.includes(type)
  }

  return {
    dictionaries,
    loading,
    DICTIONARY_TYPES,
    SPECIAL_VALUE_TYPES,
    getDictionary,
    getDictionaries,
    preloadCommonDictionaries,
    clearDictionary,
    clearAll,
    getDictionaryOptions,
    isSpecialType
  }
})
